// =============================================================
// CRandom
// ---------------------------------------
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr or woorung@nhncorp.com
// Date : Oct. 9, 2007
// =============================================================
#include "CRandom.h"

#include "lock/CLock.h"

int CRandom::seed = 1;

CRandom::CRandom()
{
	synchronized_randomize();
}

CRandom::~CRandom()
{
}

long long CRandom::millitime()
{
	struct timeb tb;
	struct tm *lt;
	ftime(&tb);
	lt = localtime(&tb.time);

	char dt[1024];
	sprintf(dt, "%d%d%d%d%d%d%d", lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec, tb.millitm);

	return strtoll(dt, (char **)NULL, 10);
}

long CRandom::microtime()
{
	struct timeval tp; 
 
	if(gettimeofday((struct timeval *)&tp,NULL)==0){ 
		return tp.tv_usec; 
	}
	else  return -1; 
} 

int CRandom::synchronized_randomize()
{
	CLock rlock(DEFAULT_RANDOM_LOCK_FILE);
	if(rlock.lock()!=0) {
		cerr << "### error : random lock failure in CRandom::synchronized_randomize()" << endl;
		exit(-1);
	}

	if(CRandom::seed==1) {
		long msec = microtime();

		CRandom::seed = msec;

		srand(CRandom::seed);
	}

	if(rlock.unlock()!=0) {
		cerr << "### error : random unlock failure in CRandom::synchronized_randomize()" << endl;
		exit(-1);
	}

	return CRandom::seed;
}

long CRandom::generate()
{
	return random();
}
